const express = require("express");
const router = express.Router();
const isEmpty = require("lodash/isEmpty");
const validator = require("validator");
const { sqlFn } = require("../mysql");
const validatorInput = (data) => {
  const errors = {};
  if (validator.isEmpty(data.username)) {
    errors.username = "请填写用户名";
  }
  if (!validator.isEmail(data.email)) {
    errors.email = "请填写邮箱号";
  }
  if (validator.isEmail(data.password)) {
    errors.password = "请填写密码";
  }
  if (validator.isEmail(data.passwordConfirmation)) {
    errors.passwordConfirmation = "请确认密码";
  }
  if (!validator.equals(data.password, data.passwordConfirmation)) {
    errors.password = "两次密码不一致";
  }
  return {
    errors,
    isValid: isEmpty(errors),
  };
};
router.post("/", (req, res) => {
  const { username, password, passwordConfirmation, email } = req.body;
  const { errors, isValid } = validatorInput(req.body);
  const sql = "insert into user (id, username, password, passwordConfirmation, email) values(?, ?, ?, ?, ?)";
  const arr = [null, username, password, passwordConfirmation, email];
  if (isValid) {
    sqlFn(sql, arr, (data) => {
      if (data.affectedRows) {
        res.send({ success: 200, errors });
      } else {
        res.status(400).json({ errors: "注册失败" });
      }
    });
  } else {
    res.status(400).json({errors});
  }
});

router.get("/", (req, res) => {
  const sql = "select * from user where username=?";
  const arr = [req.query.username];

  sqlFn(sql, arr, (data) => {
    if (data) res.send(data);
    else res.send({});
  });
});
module.exports = router;
